<template>
  <div class="editor-container">
    <textarea :id="id" ref="textarea" :value="modelValue"></textarea>
  </div>
</template>

<script>
export default {
  name: 'Editor',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    height: {
      type: [Number, String],
      default: 500
    },
    language: {
      type: String,
      default: 'zh_CN'
    },
    plugins: {
      type: String,
      default: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table paste help wordcount'
    },
    toolbar: {
      type: String,
      default: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help'
    },
    menubar: {
      type: String,
      default: 'file edit view insert format tools table help'
    }
  },
  data() {
    return {
      id: 'editor-' + Date.now(),
      hasInit: false,
      tinymceInstance: null
    }
  },
  watch: {
    modelValue(val) {
      if (this.tinymceInstance && this.hasInit && val !== this.tinymceInstance.getContent()) {
        this.tinymceInstance.setContent(val || '');
      }
    },
    disabled(val) {
      if (this.tinymceInstance && this.hasInit) {
        this.tinymceInstance.setMode(val ? 'readonly' : 'design');
      }
    }
  },
  mounted() {
    // 确保TinyMCE脚本已加载
    this.checkTinyMCE();
  },
  beforeUnmount() {
    this.destroyTinymce();
  },
  methods: {
    checkTinyMCE() {
      if (typeof window.tinymce !== 'undefined') {
        this.initTinymce();
      } else {
        console.warn('TinyMCE not found, waiting for it to load...');
        // 如果TinyMCE还没加载完成，等待一段时间再尝试
        setTimeout(() => {
          this.checkTinyMCE();
        }, 300);
      }
    },
    
    initTinymce() {
      const _this = this;
      window.tinymce.init({
        selector: `#${this.id}`,
        height: this.height,
        plugins: this.plugins,
        toolbar: this.toolbar,
        menubar: this.menubar,
        language: this.language,
        language_url: `/tinymce/langs/${this.language}.js`, // 指定语言包的路径
        branding: false,     // 隐藏TinyMCE品牌
        default_link_target: '_blank',
        setup: (editor) => {
          this.tinymceInstance = editor;
          editor.on('init', () => {
            _this.hasInit = true;
            editor.setContent(_this.modelValue || '');
            if (_this.disabled) {
              editor.setMode('readonly');
            }
          });
          editor.on('input change undo redo', () => {
            const content = editor.getContent();
            _this.$emit('update:modelValue', content);
            _this.$emit('change', content);
          });
        }
      });
    },
    
    destroyTinymce() {
      if (this.tinymceInstance) {
        try {
          this.tinymceInstance.destroy();
        } catch (e) {
          console.error('Error destroying TinyMCE', e);
        }
        this.tinymceInstance = null;
      }
    },
    
    getContent() {
      return this.tinymceInstance ? this.tinymceInstance.getContent() : '';
    },
    
    setContent(content) {
      if (this.tinymceInstance) {
        this.tinymceInstance.setContent(content || '');
      }
    },
    
    execCommand(command, value = null) {
      if (this.tinymceInstance) {
        this.tinymceInstance.execCommand(command, false, value);
      }
    }
  }
}
</script>

<style scoped>
.editor-container {
  position: relative;
  width: 100%;
  height: 100%;
}
</style>
